import React, { useRef, useEffect, useState } from 'react';

interface LazyImageProps {
  src: string;
  alt: string;
  loadingSrc?: string;
}

export const LazyImage: React.FC<LazyImageProps> = ({ src, alt, loadingSrc }) => {
  const [isLoading, setIsLoading] = useState(true);
  const imageRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    const observerOptions = {
      root: null,
      rootMargin: '0px',
      threshold: 0.1,
    };

    const handleIntersection = (entries: IntersectionObserverEntry[]) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const lazyImage = entry.target as HTMLImageElement;
          lazyImage.src = lazyImage.dataset.src || '';
          observer.unobserve(lazyImage);
        }
      });
    };

    const observer = new IntersectionObserver(handleIntersection, observerOptions);

    if (imageRef.current) {
      observer.observe(imageRef.current);
    }

    return () => {
      if (imageRef.current) {
        observer.unobserve(imageRef.current);
      }
    };
  }, []);

  const handleImageLoaded = () => {
    setIsLoading(false);
  };

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      {isLoading && <img src={loadingSrc} alt="Loading" />}
      <img
        ref={imageRef}
        data-src={src}
        alt={alt}
        onLoad={handleImageLoaded}
        style={{ display: isLoading ? 'none' : 'block' }}
      />
    </div>
  );
};

export default LazyImage;
